package hk.ust.cse.comp3111.studentSchedule;

import hk.ust.cse.comp3111.studentSchedule.ViewCalendar_week.MyListener;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.ContentUris;
import android.database.Cursor;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class ViewCalendar_day extends Fragment {
	
	TextView pDay;
	TextView nDay;
	 static final long oneD=86400000L;
	 Calendar cal = Calendar.getInstance();
	 Bundle args=null;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
		
		
		
		try {
			args = getArguments();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		if(args!=null){
			long startTime = Long.parseLong(args.getString("startTime"))+1;
			cal.setTimeInMillis(startTime);
			
		}
		
		else {
		cal.clear(Calendar.HOUR_OF_DAY);
		cal.clear(Calendar.AM_PM);
		cal.clear(Calendar.MINUTE);
		cal.clear(Calendar.SECOND);
		cal.clear(Calendar.MILLISECOND);
		}
 
        View rootView = inflater.inflate(R.layout.calendar_daily, container, false);
        
        String columns[] = new String[] { "calendar_id", "title", "description", "event_id", "startDay", "startMinute", "endMinute"};
        Cursor cur = null; 
        
        Uri.Builder eventsUriBuilder1 = CalendarContract.Instances.CONTENT_URI.buildUpon();
		ContentUris.appendId(eventsUriBuilder1, cal.getTimeInMillis());
		ContentUris.appendId(eventsUriBuilder1, cal.getTimeInMillis()+oneD);
		Uri eventsUri = eventsUriBuilder1.build();   
		
		cur = this.getActivity().getContentResolver().query(eventsUri, columns, null, null, CalendarContract.Instances.DTSTART + " ASC");
		
		//Toast.makeText(this.getActivity().getApplicationContext(), String.valueOf(cal.getTimeInMillis()), Toast.LENGTH_LONG).show();
		//Toast.makeText(this.getActivity().getApplicationContext(), String.valueOf(cal.getTimeInMillis()+oneD), Toast.LENGTH_LONG).show();
		
		if (cur.moveToFirst()) {
		//Toast.makeText(this.getActivity().getApplicationContext(), cur.getString(3), Toast.LENGTH_LONG).show();
		}
		if (cur.moveToFirst()) {
            do {
            	long eventIDs=Long.parseLong(cur.getString(3));
            	//do
            	View p4 = rootView.findViewById(R.id.sundayRelativeLayout);
                View Paper4 = new View(p4.getContext());
                TextView tv4=new TextView(this.getActivity());
                int h=(int) ((Integer.parseInt(cur.getString(6))-Integer.parseInt(cur.getString(5)))*1.5);
                RelativeLayout.LayoutParams params4 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, h);
                //int k=(int) (Long.parseLong(cur.getString(5))*1.5);
                params4.setMargins(0, (int) (Long.parseLong(cur.getString(5))*1.5), 6, 0); //1380-"*60"=
                tv4.setLayoutParams(params4);
                tv4.setText(cur.getString(1).toString());
                tv4.setBackgroundColor(Color.MAGENTA);
                ((RelativeLayout)p4).addView(tv4);
                
                String temp=tv4.getText().toString();
                MyListener listener = new MyListener();
                listener.setName(temp);
                listener.setValue(eventIDs);
                listener.setTime(cal.getTimeInMillis(), cal.getTimeInMillis()+oneD);
                tv4.setOnClickListener(listener);
                
                
                //Toast.makeText(this.getActivity().getApplicationContext(), cur.getString(1), Toast.LENGTH_LONG).show();
            } while (cur.moveToNext());
        }
		
         
        return rootView;
    }
	
	@Override
	public void onStart() {
		super.onStart();
		
		
		
		
		
		
		
		
		
        SimpleDateFormat dateFormat = new SimpleDateFormat("d MMM");
		SimpleDateFormat dateFormatGetWeekDay = new SimpleDateFormat("E");
		String today=dateFormat.format(cal.getTime()).toString();
		String weekDays = dateFormatGetWeekDay.format(cal.getTime()).toUpperCase();
		
		TextView day = (TextView) this.getActivity().findViewById(R.id.sundayTextView);
		day.setText(today+", "+weekDays);
		
		pDay = (TextView) this.getActivity().findViewById(R.id.pDay);
		nDay = (TextView) this.getActivity().findViewById(R.id.nDay);
		
		
		
        final long todayStartTime=cal.getTimeInMillis();
       
		
		pDay.setOnClickListener(new OnClickListener() {

		    public void onClick(View v) {
		    	refresh(todayStartTime-oneD);

		    }
		 });
		
		nDay.setOnClickListener(new OnClickListener() {

		    public void onClick(View v) {
		    	refresh(todayStartTime+oneD);

		    }
		 });
		
		
	}
	
	private void refresh(long startTime) {
    	Bundle save=new Bundle();
		save.putString("startTime",String.valueOf(startTime));
		Fragment fragment = new ViewCalendar_day();
		fragment.setArguments(save); 
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.frame_container, fragment).commit();
		
	}
	
	private void push(String eventID,String start, String end) {
    	Bundle save=new Bundle();
		save.putString("eventID",eventID);
		save.putString("start", start);
		save.putString("end", end);
		Fragment fragment = new ViewCalendar_singleItem();
		fragment.setArguments(save); 
		FragmentManager fragmentManager = getFragmentManager();
		fragmentManager.beginTransaction()
				.replace(R.id.frame_container, fragment).commit();
		
	}
	
	class MyListener implements OnClickListener
	{ 
	    String nulls;
	    long eventID;
	    long start;
	    long end;

	    void setName(String newName)
	    {
	    	nulls = newName;
	    }

	    void setValue(long newValue)
	    {
	    	eventID = newValue;
	    }
	    
	    void setTime(long a, long b)
	    {
	        start =a;
	        end =b;
	    }
	    
	    
	    public void onClick(View v) 
	    {
	    	Activity activity = getActivity();
	        // Use the data for some unknown purpose
	    	//Toast.makeText(activity,"you clicked ID "+value,Toast.LENGTH_LONG).show();
	    	push(String.valueOf(eventID),String.valueOf(start),String.valueOf(end));
	    	//Toast.makeText(activity,"you clicked ID "+eventID,Toast.LENGTH_LONG).show();
	    	//Toast.makeText(activity,"time "+start,Toast.LENGTH_LONG).show();
	    	//Toast.makeText(activity,"time "+end,Toast.LENGTH_LONG).show();
	    }


	}
	

}
